﻿
Partial Class App_Schedule
    Inherits MyUI.PageBaseApp

    Public CurrAccount As mDB.Account
    Public CurrTask As mDB.Task_Send

#Region "PAGE"

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        CurrAccount = CurrUser.CurrAccount

        If Not Me.IsPostBack Then
            SetDataPage()
        Else
            GetCurrTask()
        End If

    End Sub


    Private Sub SetDataPage()

        ResetTask()
        SetListTask()
        SetListNextPost()
        'SetListAccountShare()

    End Sub

#End Region


#Region "TASK"

    Private Sub GetCurrTask()


        CurrTask = CurrAccount.Tab_Task_Send.GetByPK(Utils.Conv.ToInt(Me.HidTaskId.Value)) '  .Tab_Account.BY.Account.Id(Utils.Conv.ToInt(Me.DdlAccount.SelectedValue)).ToObj

    End Sub
    Protected Sub SetListTask()
        Dim List = Me.ListTask
        Dim dt = CurrAccount.Tab_Task_Send.ToList()

        Dim DataBing = UI.ListData.Bind(Me.ListTask, dt, {"id"})


        For Each row In List.Items
            Dim task As mDB.Task_Send = DataBing(UI.ListDataItem.GetIndexData(row))   '  dd(UI.ListDataItem.GetIndexData(gr))

            Dim label = UI.ListDataItem.GetLabel(row, "LblStatus")

            If Not CBool(task.Enabled_Task) Then
                label.Text = "DISABLE"
                label.CssClass = "schedule-row-status-disable"
            ElseIf CBool(task.Expired_Task) Then
                label.Text = "EXPIRED"
                label.CssClass = "schedule-row-status-disable"
            ElseIf task.Next_Send_Date = Date.MinValue Then
                label.Text = "COMPLETED"
                label.CssClass = "schedule-row-status-completed"
            Else
                label.Text = "READY"
                label.CssClass = "schedule-row-status-ready"

            End If

        Next

        Me.UpPTaskList.Update()

    End Sub
    Private Sub SetDataTask()
        Dim lang = DB.TAB.Language.ToList



        'classe to pagina per modifica
        Me.HidTaskId.Value = CurrTask.Id
        Me.ChkEnabledTask.Checked = CurrTask.Enabled_Task
        Me.TxtDescription.Text = CurrTask.Description
        Me.ChkRepeatSendPost.Checked = CurrTask.Repeat_Send_Post
        Me.TxtSendMaxDay.Text = CurrTask.Send_Max_Day
        'Me.ChkSendAllPost.Checked = CurrTask.Send_All_Post


        Me.ListTaskType.SelectedIndex = 0
        SetListTaskType()

        '---------------------------------------------
        'SHARE
        Me.ChkShareAllPost.Checked = CurrTask.Share_All_Post
        Me.SetListAccountShare()

        '---------------------------------------------
        'AUTO POST

        UI.List.Bind(Me.DdlAutoPostLinkTypeId, MyApp.EnumToDic(Of mDB._Account_Link.Type), "value", "key", CurrTask.Auto_Post_Filter.IdsLink, True)
        Me.DdlAutoPostLinkTypeId.Items.Insert(0, New ListItem("-- Select  --", "0"))
        UI.List.Bind(Me.DdlAutoPostLanguage, lang, "language", "lang_code", CurrTask.Auto_Post_Filter.IdsLang, True)
        UI.List.Bind(Me.DdlAutoPostLanguageNot, lang, "language", "lang_code", CurrTask.Auto_Post_Filter.IdsLangNot, True)


        'Me.ChkAutoPostActive.Checked = CurrTask.Auto_Post_Active
        Me.ChkAutoPostPrivate.Checked = CurrTask.Auto_Post_Private

        'Me.TxtAutoPostText.Text = CurrTask.Auto_Post_Text


        If CurrTask.Auto_Post_Text_List.Count >= 1 Then Me.TxtAutoPostText1.Text = CurrTask.Auto_Post_Text_List(0)
        If CurrTask.Auto_Post_Text_List.Count >= 2 Then Me.TxtAutoPostText2.Text = CurrTask.Auto_Post_Text_List(1)
        If CurrTask.Auto_Post_Text_List.Count >= 3 Then Me.TxtAutoPostText3.Text = CurrTask.Auto_Post_Text_List(2)
        If CurrTask.Auto_Post_Text_List.Count >= 4 Then Me.TxtAutoPostText4.Text = CurrTask.Auto_Post_Text_List(3)
        If CurrTask.Auto_Post_Text_List.Count >= 5 Then Me.TxtAutoPostText5.Text = CurrTask.Auto_Post_Text_List(4)

        'CurrTask.Auto_Post_Text_List = New List(Of String) From {Me.TxtAutoPostText.Text, Me.TxtAutoPostText2.Text}


        'Me.CtrAutoPost.PrivatePost = CurrTask.Auto_Post_Private
        'Me.CtrAutoPost.PostText = CurrTask.Auto_Post_Text

        'Me.ChkAutoPostPrivate.Checked = CurrTask.Auto_Post_Private
        'Me.TxtAutoPostText.Text = CurrTask.Auto_Post_Text

        '---------------------------------------------
        'IMPORTA
        Dim Cat = CurrAccount.
            Tab_Categorize_Follower.
            REL.Categorize_Follower.Categorize.
            SetSelect("Categorize.*").
        ToDataTable()
        UI.List.Bind(Me.DdlCategories, Cat, "description", "id", "", False)
        UI.List.Bind(Me.DdlCategoriesNot, Cat, "description", "id", "", False)

        UI.List.Bind(Me.DdlLinkType, MyApp.EnumToDic(Of mDB._Account_Link.Type), "value", "key", "", False)

        Dim gender = MyApp.EnumToDic(Of mDB.Gender_Name.Type)()
        gender.Remove(mDB.Gender_Name.Type.NOT_ASSIGNED)
        UI.List.Bind(Me.DdlGender, gender, "value", "key", "", False)

        UI.List.Bind(Me.DdlLanguage, lang, "language", "lang_code", "", False)
        UI.List.Bind(Me.DdlLanguageNot, lang, "language", "lang_code", "", False)

        Dim business = MyApp.EnumToDic(Of mDB.Account.BusinessType)()
        business.Remove(mDB.Account.BusinessType.NOT_ASSIGNED)
        UI.List.Bind(Me.DdlBusiness, business, "value", "key", "", False)

        Dim Status = MyApp.EnumToDic(Of mDB.Account.StatusType)()
        Status.Remove(mDB.Account.StatusType.NOT_ASSIGNED)
        UI.List.Bind(Me.DdlStatus, Status, "value", "key", "", False)

        Dim hashtag = CurrAccount.Tab_Query_Listen.ToDataTable
        'UI.List.Bind(Me.DdlHashtag, hashtag, "query", "id", "", False)


        '---------------------------------------------
        'DETTAGLI
        SetListTakSched()
        SetListTaskPost(False)



    End Sub
    Private Function SaveDataTask(AddSched As Boolean) As Boolean
        Dim AddNew = CurrTask Is Nothing



        Dim vv As New UI.Validator.ValidatorGroup
        'vv.val.Add(New UI.Validator.ValidatorUIItem(New UI.Validator.Validators.RequiredValidator(Me.TxtDescription.Text), Me.lll))
        vv.val.Add(UI.Validator.UIValidators.Required(Me.TxtDescription, Me.lll))

        vv.val.Add(New UI.Validator.ValidatorUI(
            Function()
                Dim err = CurrTask Is Nothing And Not AddSched
                Me.LblErrSchedule.Visible = err
                Return err
            End Function
        ))


        If vv.ValidatorCheck.Count = 0 Then

            If AddNew Then
                CurrTask = New mDB.Task_Send
                DB.TAB.Task_Send.InsertOnSubmit(CurrTask)
            End If

            Me.GetDataTask()

            If Not AddNew Then
                CurrTask.SetNextSend()
            End If

            DB.SubmitChanges()
            Me.SetDataTask()
            'Me.HidTaskId.Value = CurrTask.Id

            Me.SetListTask()

            Return True
        Else
            Return False
        End If

    End Function
    Private Sub GetDataTask()

        'modifica dati
        CurrTask.Enabled_Task = Me.ChkEnabledTask.Checked
        CurrTask.Account_Id = CurrAccount.Id
        CurrTask.Description = Me.TxtDescription.Text
        CurrTask.Repeat_Send_Post = Me.ChkRepeatSendPost.Checked
        CurrTask.Send_Max_Day = Utils.Conv.ToInt(Me.TxtSendMaxDay.Text)
        'CurrTask.Send_All_Post = Me.ChkSendAllPost.Checked

        '---------------------------------------------
        'SHARE
        CurrTask.Share_All_Post = Me.ChkShareAllPost.Checked

        '---------------------------------------------
        'AUTO POST

        'IMPORTANTE se cambio il tipo di stato mette la data di ultiomo aggiornamento a ora
        Dim OldLink = ""
        If CurrTask.Auto_Post_Filter.IdsLink.Count > 0 Then
            OldLink = CurrTask.Auto_Post_Filter.IdsLink(0).ToString
        End If
        If OldLink <> Me.DdlAutoPostLinkTypeId.SelectedValue Then
            CurrTask.Auto_Post_Last_Update = Date.UtcNow
        End If

        'CurrTask.Auto_Post_Active = Me.ChkAutoPostActive.Checked
        CurrTask.Auto_Post_Private = Me.ChkAutoPostPrivate.Checked

        CurrTask.Auto_Post_Text_List = New List(Of String) From {
            Me.TxtAutoPostText1.Text,
            Me.TxtAutoPostText2.Text,
            Me.TxtAutoPostText3.Text,
            Me.TxtAutoPostText4.Text,
            Me.TxtAutoPostText5.Text
        }

        Dim Filter = New mDB.Account.Filter With {
            .IdsLink = UI.List.GetSelectValuesInt(Me.DdlAutoPostLinkTypeId),
            .IdsLang = UI.List.GetSelectValues(Me.DdlAutoPostLanguage),
            .IdsLangNot = UI.List.GetSelectValues(Me.DdlAutoPostLanguageNot)
        }
        CurrTask.Auto_Post_Filter = Filter



    End Sub

    Protected Sub ListTask_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListTask.ItemCommand
        Dim List As ListView = sender
        Dim Row = UI.ListDataItem.GetRow(e.CommandSource)

        If Row IsNot Nothing Then

            Dim id = UI.ListDataItem.GetKey(e.CommandSource)
            CurrTask = CurrAccount.Tab_Task_Send.GetByPK(id)

            Select Case e.CommandName
                Case "EDIT_ROW"
                    SetDataTask()
                    Me.UpPTaskEdit.Update()

                Case "DELETE_ROW"
                    DB.TAB.Task_Send.DeleteOnSubmit(CurrTask)
                    DB.SubmitChanges()
                    Me.SetListTask()

            End Select

        End If
    End Sub

    Protected Sub BtnAddListPosts_Click(sender As Object, e As System.EventArgs) Handles BtnAddListPosts.Click


        Dim FromDate As Date = Date.MinValue
        Dim ToDate As Date = Date.MinValue
        Date.TryParse(Me.TxtBeginDate.Text, FromDate)
        Date.TryParse(Me.TxtEndDate.Text, ToDate)

        Dim q = CurrAccount.View_AccountLink_ByFilter(New mDB.Account.Filter With {
                .FromDate = FromDate, .ToDate = ToDate,
                .IdsLink = UI.List.GetSelectValuesInt(Me.DdlLinkType),
                .IdsBusin = UI.List.GetSelectValuesInt(Me.DdlBusiness),
                .IdsStatus = UI.List.GetSelectValuesInt(Me.DdlStatus),
                .IdsCat = UI.List.GetSelectValuesInt(Me.DdlCategories),
                .IdsCatNot = UI.List.GetSelectValuesInt(Me.DdlCategoriesNot),
                .IdsGend = UI.List.GetSelectValuesInt(Me.DdlGender),
                .IdsLang = UI.List.GetSelectValues(Me.DdlLanguage),
                .IdsLangNot = UI.List.GetSelectValues(Me.DdlLanguageNot)
            }).
            Where("excluded", "=", False).
            GroupBy("account.id")

        CurrTask.AddPosts(
            New mDB.Task_Post With {
                .Post_Text = Me.CtrListPost.PostText,
                .Post_Type_Id = IIf(Me.CtrListPost.PrivatePost, 1, 0),
                .Media_Id = Utils.Conv.ToInt(CtrListPost.MediaID)
            }, q.ToList(Of mDB.Account), True
        )

        Me.SetListTaskPost(False)

    End Sub
    'Protected Sub BtnAddListenPosts_Click(sender As Object, e As EventArgs) Handles BtnAddListenPosts.Click

    '    Dim FromDate As Date = Date.MinValue
    '    Dim ToDate As Date = Date.MinValue
    '    Date.TryParse(Me.TxtBeginDate.Text, FromDate)
    '    Date.TryParse(Me.TxtEndDate.Text, ToDate)

    '    Dim qQueries = CurrAccount.Tab_Query_Listen     'CurrUser.Tab_Query.BY.Query.Real_Time(1)
    '    Dim ids = UI.List.GetSelectValuesInt(Me.DdlHashtag) '   (From i In Me.DdlHashtag.GetSelectedIndices Select CInt(Me.DdlHashtag.Items(i).Value)).ToList
    '    If ids.Count <> 0 Then
    '        qQueries.Where("query.id", "IN", ids)
    '    End If
    '    Dim queries = qQueries.ToList

    '    Dim q As New List(Of String)
    '    'Dim qque = New List(Of DBase.MySql.SqlQuery(Of mDB._Query_Account))
    '    For Each q2 In queries

    '        'qque.Add(q2._Tab_Query_Account)

    '        Dim pp = q2._Tab_Query_Account.REL._Query_Account.Account.REL.Account.Account_Link.BY.Account_Link.Account_Id(CurrAccount.Id, GloukDB.Account_Link.Type.FOLLOWER).
    '        GroupBy("account_username").
    '        SetSelect("account_username").
    '    ToList(Of String)()

    '    Next

    '    Dim q = DB.GetQuery.From(DB.UnionQuery(qque), "query_account", "").
    '        Join("account", "account_code", "query_account.account_code").
    '        Join("account_link", "account_link_id", "account.id").
    '        Where("account_id", "=", CurrAccount.Id).
    '        Where("link_type_id", "=", mDB.Account_Link.Type.FOLLOWER).
    '        GroupBy("account_username").
    '        SetSelect("account_username").
    '    ToList(Of String)()

    '    CurrTask.AddPosts(
    '        New mDB.Task_Post With {
    '            .Post_Text = Me.CtrListPost.PostText,
    '            .Post_Type_Id = DB.ToBool(Me.CtrListPost.PrivatePost),
    '            .Media_Id = Utils.Conv.ToInt(CtrListPost.MediaID)
    '        }, q
    '    )

    '    Me.SetListTaskPost(False)

    'End Sub
    'Protected Sub BtnAddListenPosts_Click(sender As Object, e As EventArgs) Handles BtnAddListenPosts.Click

    '    Dim FromDate As Date = Date.MinValue
    '    Dim ToDate As Date = Date.MinValue
    '    Date.TryParse(Me.TxtBeginDate.Text, FromDate)
    '    Date.TryParse(Me.TxtEndDate.Text, ToDate)

    '    Dim qQueries = CurrAccount.Tab_Query_Listen     'CurrUser.Tab_Query.BY.Query.Real_Time(1)
    '    Dim ids = UI.List.GetSelectValuesInt(Me.DdlHashtag) '   (From i In Me.DdlHashtag.GetSelectedIndices Select CInt(Me.DdlHashtag.Items(i).Value)).ToList
    '    If ids.Count <> 0 Then
    '        qQueries.Where("query.id", "IN", ids)
    '    End If
    '    Dim queries = qQueries.ToList

    '    Dim q As New List(Of Integer)
    '    'Dim qque = New List(Of DBase.MySql.SqlQuery(Of mDB._Query_Account))
    '    For Each q2 In queries

    '        'qque.Add(q2._Tab_Query_Account)

    '        q.AddRange(q2._Tab_Query_Account.
    '            REL._Query_Account.Account.
    '            REL.Account.Account_Link.
    '            BY.Account_Link.Account_Id(CurrAccount.Id, GloukDB.Account_Link.Type.FOLLOWER).
    '            GroupBy("account.id").
    '            SetSelect("account.id").
    '        ToList(Of Integer))

    '    Next

    '    q = q.Distinct.ToList

    '    Dim Accounts = DB.TAB.Account.Where("id", "IN", q).ToList

    '    CurrTask.AddPosts(
    '        New mDB.Task_Post With {
    '            .Post_Text = Me.CtrListPost.PostText,
    '            .Post_Type_Id = IIf(Me.CtrListPost.PrivatePost, 1, 0),
    '            .Media_Id = Utils.Conv.ToInt(CtrListPost.MediaID)
    '        }, Accounts, True
    '    )

    '    Me.SetListTaskPost(False)

    'End Sub

    Protected Sub BtnAddMultiPosts_Click(sender As Object, e As System.EventArgs) Handles BtnAddMultiPosts.Click


        Dim Posts = Me.TxtListpost.Text.Split({vbLf}, StringSplitOptions.RemoveEmptyEntries)


        For Each p In Posts

            p = Replace(p, "{br}", vbCrLf, , , CompareMethod.Text)

            Dim Post = New mDB.Task_Post With {
                .Post_Text = p,
                .Task_Send_Id = CurrTask.Id
            }

            CurrTask.AddPost(Post)
            'DB.TAB.Task_Post.InsertOnSubmit(Post)
            'DB.SubmitChanges()

            CurrTask.MovePost(Post, mDB.Task_Send.MovePostType.END)

        Next

        Me.CtrListPost.PostText = ""
        Me.SetListTaskPost(False)


    End Sub

    Protected Sub BtnTaskEditNext_Click(sender As Object, e As EventArgs) Handles BtnTaskEditNext.Click

        If Me.SaveDataTask(False) Then
            Me.SetDataTask()
            Me.PnlTaskEditWiz1.Visible = False
            Me.PnlTaskEditWiz2.Visible = True
        End If


    End Sub
    Protected Sub BtnTaskEditPrev_Click(sender As Object, e As EventArgs) Handles BtnTaskEditPrev.Click
        Me.PnlTaskEditWiz1.Visible = True
        Me.PnlTaskEditWiz2.Visible = False
    End Sub
    Protected Sub BtnTaskEditSaveClose_Click(sender As Object, e As EventArgs) Handles BtnTaskEditSaveClose.Click, BtnTaskEditSaveClose2.Click

        If Me.SaveDataTask(False) Then
            'Me.SetListTask()
            Me.ResetTask()
        End If

    End Sub

    Protected Sub BtnTaskEditClose_Click(sender As Object, e As EventArgs) Handles BtnTaskEditClose.Click, BtnTaskEditClose2.Click

        Me.ResetTask()

    End Sub

    Private Sub ResetTask()

        CurrTask = (New mDB.Task_Send).SetDefault
        SetDataTask()


        Me.PnlTaskEditWiz1.Visible = True
        Me.PnlTaskEditWiz2.Visible = False

        Me.PnlTaskPost.Visible = False

        'Me.PnlTaskEdit.Visible = True
        'Me.BtnUpdate.Text = "CONTINUA -->"
        'Me.PnlTaskConfEdit.Visible = False


        Me.UpPTaskEdit.Update()
        Me.UpPTaskPost.Update()

    End Sub

    Private Sub SetListTaskType()

        Dim tasktype = New List(Of Object) From {
            {New With {.id = "1", .text = "tweet", .select = False, .Css = "wizard-tab-tweet"}},
            {New With {.id = "2", .text = "share", .select = False, .Css = "wizard-tab-share"}},
            {New With {.id = "3", .text = "engage", .select = False, .Css = "wizard-tab-engage"}},
            {New With {.id = "4", .text = "connect", .select = False, .Css = "wizard-tab-connect"}}
        }

        'Dim osel = tasktype.Find(Function(o) o.id = selid)
        'osel.select = True
        'Me.ListTaskType.SelectedIndex = tasktype.IndexOf(osel)
        If Me.ListTaskType.SelectedIndex <> -1 Then
            tasktype(Me.ListTaskType.SelectedIndex).select = True
        End If
        UI.ListData.Bind(Me.ListTaskType, tasktype, {"id"})

        Me.PnlTaskType1.Visible = Me.ListTaskType.SelectedValue = 1
        Me.PnlTaskType2.Visible = Me.ListTaskType.SelectedValue = 2
        Me.PnlTaskType3.Visible = Me.ListTaskType.SelectedValue = 3
        Me.PnlTaskType4.Visible = Me.ListTaskType.SelectedValue = 4



    End Sub
    Protected Sub ListTaskType_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListTaskType.ItemCommand

        ListTaskType.SelectedIndex = e.Item.DisplayIndex
        'SetListTaskType(UI.ListDataItem.GetKey(e.CommandSource))
        SetListTaskType()
    End Sub


#End Region

#Region "TASK SCHEDULE"

    Protected Sub ChkRangeTime_Checked(sender As CheckBox, e As System.EventArgs)
        'Dim gr = UI.GridRow.GetRow(sender)

        'UI.GridRow.GetPanel(gr, "PnlRange").Visible = sender.Checked


    End Sub
    Protected Sub ChkEveryDay_Checked(sender As CheckBox, e As System.EventArgs)
        'Dim gr = UI.GridRow.GetRow(sender)

        'UI.GridRow.GetPanel(gr, "PnlEveryDay").Visible = sender.Checked

    End Sub
    Protected Sub SetListTakSched()

        If CurrTask.Id = 0 Then
            ''            UI.ListData.Clear(Me.ListTaskShed)
            UI.ListData.Bind(Me.ListTaskShed, New List(Of Object))
            'Me.ListTaskShed.DataSource = Nothing
            'Me.ListTaskShed.DataBind()

            Me.PnlTaskShedAdd.Visible = True
            Me.PnlTaskShedEdit.Visible = False
        Else
            Dim dt = CurrTask.Tab_Task_Scheduler.ToList
            UI.ListData.Bind(Me.ListTaskShed, dt, {"id"})
        End If

        Me.UpPTaskEdit.Update()

    End Sub
    Protected Sub BtnTaskSchedAdd_Click(sender As Object, e As System.EventArgs) Handles BtnTaskSchedAdd.Click

        Me.PnlTaskShedEdit.Visible = True
        Me.PnlTaskShedAdd.Visible = False

        'If CurrTask Is Nothing Then
        '    If Me.SaveDataTask Then
        '        Me.SetDataTask()
        '    End If
        'End If

        UI.ListData.Bind(ListTaskShedEdit, New Object() {(New mDB.Task_Scheduler).SetDefault}, {"id"})


    End Sub

    Protected Sub ListTaskShed_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListTaskShed.ItemCommand
        Dim List As ListView = sender
        Dim Row = UI.ListDataItem.GetRow(e.CommandSource)

        If Row IsNot Nothing Then

            Dim id = UI.ListDataItem.GetKey(e.CommandSource)
            Dim TaskShed = DB.TAB.Task_Scheduler.GetByPK(id)



            Select Case e.CommandName
                Case "EDIT_ROW"

                    PnlTaskShedEdit.Visible = True
                    PnlTaskShedAdd.Visible = Not PnlTaskShedEdit.Visible
                    UI.ListData.Bind(ListTaskShedEdit, New Object() {TaskShed}, {"id"})


                Case "DELETE_ROW"


                    DB.TAB.Task_Scheduler.DeleteOnSubmit(TaskShed)
                    DB.SubmitChanges()

                    Me.SetListTakSched()
            End Select

        End If
    End Sub
    Protected Sub BtnAddNexThours_Click(sender As Object, e As EventArgs) Handles BtnAddNexThours.Click

        If CurrTask Is Nothing Then
            SaveDataTask(True)
        End If

        If CurrTask IsNot Nothing Then

            Dim pnext = Me.TxTNextHours.Text.Split(",")

            For Each n In pnext

                Dim TaskShed = New mDB.Task_Scheduler With {.Task_Send_Id = CurrTask.Id}
                DB.TAB.Task_Scheduler.InsertOnSubmit(TaskShed)

                TaskShed.Begin_Date = Date.UtcNow.AddHours(Utils.Conv.ToInt(n))
                '            TaskShed.Begin_Date = TaskShed.Begin_Date.Add(Utils.Conv.ToTimeSpan(UI.ListDataItem.GetTextBox(Row, "TxtRepeatFromTime").Text))

                'Shed.Repeat_From_Time = DBase.Conv.TimeToDB(UI.Grid.GetTextBox(g, gr.RowIndex, "TxtRepeatFromTime").Text)
                'TaskShed.Repeat_Day = False
                'TaskShed.End_Date = Utils.Conv.ToDate(UI.ListDataItem.GetTextBox(Row, "TxtEndDate").Text)
                'TaskShed.Range_Time = UI.ListDataItem.GetCheckBox(Row, "ChkRangeTime").Checked

                'TaskShed.Repeat_To_Time = DBase.Conv.TimeToDB(UI.ListDataItem.GetTextBox(Row, "TxtRepeatToTime").Text)
                'TaskShed.Repeat_Every_Time = DBase.Conv.TimeToDB(UI.ListDataItem.GetTextBox(Row, "TxtRepeatEveryTime").Text)

                'Dim listDay = UI.ListDataItem.GetControl(Of ListView)(Row, "ListRepeatDay")

                'Dim rep = TaskShed.Repeat_Day_Week
                'For Each r In listDay.Items
                '    Dim key = UI.ListDataItem.GetKey(r)

                '    rep(key) = IIf(UI.ListDataItem.GetCheckBox(r, "ChkRepeatDay").Checked, 1, 0)
                'Next
                'TaskShed.Repeat_Day_Week = rep

                DB.SubmitChanges()



            Next


            Me.SetListTakSched()
        End If


    End Sub

    Protected Sub ListTaskShedEdit_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListTaskShedEdit.ItemCommand
        Dim List As ListView = sender
        Dim Row = UI.ListDataItem.GetRow(e.CommandSource)

        If Row IsNot Nothing Then

            Dim id = UI.ListDataItem.GetKey(e.CommandSource)
            Dim TaskShed = DB.TAB.Task_Scheduler.GetByPK(id)

            Select Case e.CommandName
                Case "UPDATE_ROW"

                    If CurrTask Is Nothing Then
                        SaveDataTask(True)
                    End If

                    If CurrTask IsNot Nothing Then

                        If TaskShed Is Nothing Then
                            TaskShed = New mDB.Task_Scheduler With {.Task_Send_Id = CurrTask.Id}
                            DB.TAB.Task_Scheduler.InsertOnSubmit(TaskShed)
                        End If

                        TaskShed.Begin_Date = Utils.Conv.ToDate(UI.ListDataItem.GetTextBox(Row, "TxtBeginDate").Text)
                        TaskShed.Begin_Date = TaskShed.Begin_Date.Add(Utils.Conv.ToTimeSpan(UI.ListDataItem.GetTextBox(Row, "TxtRepeatFromTime").Text))
                        TaskShed.Begin_Date = CurrAccount.UtcDate(TaskShed.Begin_Date)

                        'Shed.Repeat_From_Time = DBase.Conv.TimeToDB(UI.Grid.GetTextBox(g, gr.RowIndex, "TxtRepeatFromTime").Text)
                        TaskShed.Repeat_Day = UI.ListDataItem.GetCheckBox(Row, "ChkEveryDay").Checked
                        TaskShed.End_Date = CurrAccount.UtcDate(Utils.Conv.ToDate(UI.ListDataItem.GetTextBox(Row, "TxtEndDate").Text))
                        TaskShed.Range_Time = UI.ListDataItem.GetCheckBox(Row, "ChkRangeTime").Checked

                        TaskShed.Repeat_To_Time = DBase.Conv.TimeToDB(Utils.Conv.ToDate(UI.ListDataItem.GetTextBox(Row, "TxtRepeatToTime").Text))
                        TaskShed.Repeat_Every_Time = DBase.Conv.TimeToDB(UI.ListDataItem.GetTextBox(Row, "TxtRepeatEveryTime").Text)

                        Dim listDay = UI.ListDataItem.GetControl(Of ListView)(Row, "ListRepeatDay")

                        Dim rep = TaskShed.Repeat_Day_Week
                        For Each r In listDay.Items
                            Dim key = UI.ListDataItem.GetKey(r)

                            rep(key) = IIf(UI.ListDataItem.GetCheckBox(r, "ChkRepeatDay").Checked, 1, 0)
                        Next
                        TaskShed.Repeat_Day_Week = rep

                        DB.SubmitChanges()

                        Me.PnlTaskShedEdit.Visible = False
                        Me.PnlTaskShedAdd.Visible = True
                        Me.SetListTakSched()

                    End If


            End Select

        End If





    End Sub


#End Region

#Region "TASK POST"

    'Protected SortGridTaskPosts As UI.SortControl

    Protected Sub SetListTaskPost()
        SetListTaskPost(False)
    End Sub

    Private Sub SetListTaskPost(AddRow As Boolean)
        Dim List = Me.ListTaskPost

        If CurrTask.Id = 0 Then
            Me.PnlTaskPost.Visible = False
        Else

            Dim q = CurrTask.Tab_Task_Post.
                Limit(1000)

            If Me.ChkViewOnlyToSend.Checked Then
                q.Where("send_post", "=", False)
            End If

            'Dim dt = Me.SortGridTaskPosts.SortQuery(q).ToList()
            Dim dt = q.ToList()

            If AddRow Then
                dt.Insert(UI.ListData.GetIndexData(List, 0), New mDB.Task_Post)
                List.EditIndex = 0
            End If

            UI.ListData.Bind(List, dt, {"id"})

            'For Each gr As GridViewRow In g.Rows
            '    Dim Post = dt(UI.GridRow.GetIndexData(gr))
            '    Dim pnl = UI.GridRow.GetPanel(gr, "PnlOrder")

            '    If pnl IsNot Nothing Then
            '        pnl.Visible = Me.SortGridTaskPosts.SortField = "order_by"
            '    End If

            'Next

            Me.PnlTaskPost.Visible = True

        End If
        Me.UpPTaskPost.Update()

        'g.Columns(3). ' = Drawing.Color.Red '  = Me.SortGridTaskPosts.SortField = "order_by"

    End Sub
    Protected Sub BtnNewPost_Click(sender As Object, e As System.EventArgs) Handles BtnNewPost.Click

        SetListTaskPost(True)

    End Sub

    Protected Sub ChkViewOnlyToSend_CheckedChanged(sender As Object, e As System.EventArgs) Handles ChkViewOnlyToSend.CheckedChanged
        SetListTaskPost(False)

    End Sub

    Protected Sub ListTaskPost_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListTaskPost.ItemCommand
        Dim List As ListView = sender
        Dim Row = UI.ListDataItem.GetRow(e.CommandSource)

        If Row IsNot Nothing Then

            Dim id = UI.ListDataItem.GetKey(e.CommandSource)
            Dim Post = DB.TAB.Task_Post.GetByPK(id)



            Select Case e.CommandName
                Case "EDIT_ROW"
                    List.EditIndex = Row.DisplayIndex


                    SetListTaskPost(False)

                    'Me.UpPElaborations.Update()
                Case "CANCEL_ROW_EDIT"

                    List.EditIndex = -1

                    SetListTaskPost(False)

                Case "UPDATE_ROW"

                    Dim NewPost As Boolean = False
                    If Post Is Nothing Then
                        Post = New mDB.Task_Post With {.Task_Send_Id = Me.HidTaskId.Value}
                        DB.TAB.Task_Post.InsertOnSubmit(Post)
                        NewPost = True
                    End If

                    Post.Send_Post = UI.ListDataItem.GetCheckBox(Row, "ChkSendPost").Checked

                    Dim CtrPost = UI.ListDataItem .GetControl(Of ASP.app_controls_postwrite_ascx)(Row, "CtrPost")

                    Post.To_Account_Username = CtrPost.ToAccount
                    Post.Post_Text = CtrPost.PostText
                    Post.Post_Type_Id = IIf(CtrPost.PrivatePost, 1, 0)
                    Post.Media_Id = CtrPost.MediaID


                    DB.SubmitChanges()

                    If NewPost Then
                        CurrTask.MovePost(Post, mDB.Task_Send.MovePostType.BEGIN)
                    End If

                    List.EditIndex = -1
                    SetListTaskPost(False)

                Case "DELETE_ROW"


                    DB.TAB.Task_Post.DeleteOnSubmit(Post)
                    DB.SubmitChanges()

                    Me.SetListTaskPost(False)

                    'SetDataQuery(False)
                Case "MOVE_PREV", "MOVE_NEXT", "MOVE_BEGIN", "MOVE_END"
                    Select Case e.CommandName

                        Case "MOVE_PREV"

                            CurrTask.MovePost(Post, mDB.Task_Send.MovePostType.PREV)
                            'g.SelectedIndex = gr.RowIndex - 1


                        Case "MOVE_NEXT"

                            CurrTask.MovePost(Post, mDB.Task_Send.MovePostType.NEXT)
                            'g.SelectedIndex = gr.RowIndex + 1


                        Case "MOVE_BEGIN"

                            CurrTask.MovePost(Post, mDB.Task_Send.MovePostType.BEGIN)
                            'g.SelectedIndex = 0


                        Case "MOVE_END"

                            CurrTask.MovePost(Post, mDB.Task_Send.MovePostType.END)
                            'g.SelectedIndex = g.Rows.Count - 1


                    End Select

                    'If g.SelectedIndex < 0 Then
                    '    g.SelectedIndex = 0
                    'End If

                    'If g.SelectedIndex > g.Rows.Count - 1 And g.PageIndex = g.PageCount - 1 Then
                    '    g.SelectedIndex = g.Rows.Count - 1
                    'End If

                    'g.SelectedIndex = -1

                    Me.ChkViewOnlyToSend.Checked = False

                    Me.SetListTaskPost(False)

            End Select

        End If
    End Sub

    Protected Sub BtnDeleteAllPosts_Click(sender As Object, e As System.EventArgs) Handles BtnDeleteAllPosts.Click

        CurrTask.DeleteAllPosts()
        Me.SetListTaskPost(False)

    End Sub

    Protected Sub BtnResetPosts_Click(sender As Object, e As System.EventArgs) Handles BtnResetPosts.Click

        CurrTask.ResetAllPosts()
        Me.SetListTaskPost(False)

    End Sub

    Protected Sub BtnRandomizePosts_Click(sender As Object, e As System.EventArgs) Handles BtnRandomizePosts.Click

        CurrTask.ReOrderPost(True)
        Me.SetListTaskPost(False)

    End Sub


#End Region

#Region "TASK ACCOUNT SHARE"
    'Protected SortGridAccountShare As UI.SortControl
    Private Sub SetListAccountShare()
        Dim List = Me.ListAccountShare

        If CurrTask.Share_Account_Id <> 0 Then
            ' Me.TxtShareAccountUsername.Text = CurrTask.Share_Account_Username
            Dim dt = DB.TAB.Account.
                REL.Account.Account_Add_Info.
                BY.Account.Id(CurrTask.Share_Account_Id).
            ToDataTable
            UI.ListData.Bind(List, dt)
        Else
            Me.TxtShareAccountUsername.Text = ""
            UI.ListData.Clear(List)
        End If


    End Sub

    Protected Sub BtnNewAccount_Click(sender As Object, e As System.EventArgs) Handles BtnNewAccount.Click

        Dim tw = New MyApp.Network.Twitter(CurrAccount.GetOauth)

        Dim AccToAdd As New List(Of String)
        AccToAdd.Add(Me.TxtShareAccountUsername.Text)


        Dim Accs = tw.DownloadAccounts(AccToAdd, Nothing)

        If Accs.Count > 0 Then
            CurrTask.Share_Account_Id = Accs(0).Id
            'CurrTask.Share_Account_Username = Me.TxtShareAccountUsername.Text
            DB.SubmitChanges()

        End If

        SetListAccountShare()

    End Sub
    Protected Sub BtnRemoveAccount_Click(sender As Object, e As System.EventArgs) Handles BtnRemoveAccount.Click

        CurrTask.Share_Account_Id = 0
        'CurrTask.Share_Account_Username = ""

        DB.SubmitChanges()
        SetListAccountShare()

    End Sub


#End Region

#Region "NEXT POST"

    Private Sub SetListNextPost()
        Dim List = Me.ListNextPost


        Dim q = DB.TAB.Task_Send.
            REL.Task_Send.Task_Scheduler.
            Where("account_id", "=", CurrAccount.Id).
            Where("enabled_task", "=", "1", "expired_task", "=", 0).
            Where("next_send_date", ">", Date.UtcNow).
            OrderBy("next_date").
            SetSelect("description",
                "if(repeat_day=0 and next_send_task_scheduler_id<>task_scheduler.id,  begin_date, next_send_date) as next_date",
                "next_send_post", "next_send_task_scheduler_id", "send_all_post")


        'select description, if (repeat_day=0 and next_send_task_scheduler_id<>task_scheduler.id,  begin_date, next_send_date) as nnnext_date,next_send_post, next_send_task_scheduler_id, send_all_post, task_scheduler.*
        'FROM task_send
        'inner join task_scheduler on task_scheduler.task_send_id = task_send.id
        'where  enabled_task = 1 and expired_task = 0 and next_send_date > CURRENT_DATE
        'order by next_date 



        'Dim dt = Me.SortGridTaskPosts.SortQuery(q).ToList()
        Dim dt = q.ToDataTable


        UI.ListData.Bind(List, dt, {})

        'For Each gr As GridViewRow In g.Rows
        '    Dim Post = dt(UI.GridRow.GetIndexData(gr))
        '    Dim pnl = UI.GridRow.GetPanel(gr, "PnlOrder")

        '    If pnl IsNot Nothing Then
        '        pnl.Visible = Me.SortGridTaskPosts.SortField = "order_by"
        '    End If

        'Next

        Me.UpPNextPost.Update()


    End Sub
#End Region





End Class
